import datetime
from email import header
from tokenize import Name
from urllib import response
import requests
import json
import time
import schedule
import jsonpath

url = "https://www.sjsggwh.com/yuyue/SubmitBook"
headers = {
    "Host": "www.sjsggwh.com",
    "Cookie": "",
    "Content-Length": "151",
    "Sec-Ch-Ua": '"(Not(A:Brand";v="8", "Chromium";v="99"',
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
    "Sec-Ch-Ua-Mobile": "?0",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36",
    "Sec-Ch-Ua-Platform": "Windows",
    "Origin": "https://www.sjsggwh.com",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "close"
}

data = {
    "Name": "",
    "IdType": "",
    "IdNumber": "",
    "Mobile": "",
    "SceneId": "",
    "FacilitiesId": 0,
    "SpaceId": 0,
    "ExtMember": []
}


def get_json_value(json_data, key_name):
    '''获取到json中任意key的值,结果为list格式'''
    key_value = jsonpath.jsonpath(
        json_data, '$..{key_name}'.format(key_name=key_name))
    # key的值不为空字符串或者为empty（用例中空固定写为empty）返回对应值，否则返回empty
    return key_value


def getSceneID(SpaceId):
    url = "https://www.sjsggwh.com/yuyue/GetSceneList?id={}".format(
        str(SpaceId))
    response = requests.get(url)
    json_content = json.loads(response.text)
    return [get_json_value(json_content, "DayName")[-1], list(get_json_value(json_content, "Id"))[-1]]


def log(date, DayName, Secent, status, usetime, user):
    with open("./Log_appointment.txt", "a") as f:
        f.write(date+"\t"+DayName+"\t"+status +
                "\t"+"用时："+usetime+"\t"+Secent+"\t"+user+"\n")


def appointment(DayName, Secent):
    eight_time_start = datetime.datetime.strptime(
        str(datetime.datetime.now().date()) + '19:59', r'%Y-%m-%d%H:%M')
    eight_time_end = datetime.datetime.strptime(
        str(datetime.datetime.now().date()) + '20:01', r'%Y-%m-%d%H:%M')
    six_time_start = datetime.datetime.strptime(
        str(datetime.datetime.now().date()) + '5:59', r'%Y-%m-%d%H:%M')
    six_time_end = datetime.datetime.strptime(
        str(datetime.datetime.now().date()) + '6:01', r'%Y-%m-%d%H:%M')
    while True:
        # 计算运行时间的开始时间 和 获取现在时间
        date = datetime.datetime.now()
        start_time = time.perf_counter()
        # 请求
        response = requests.post(url, data=json.dumps(
            data), headers=headers, timeout=60)

        # 请求成功
        if(response.text == '{"state":"1","content":"预约成功"}'):
            # 计算运行时间的结束时间
            end_time = time.perf_counter()
            # 记录日志
            log(str(date), DayName, Secent, "预约成功", format(
                round(end_time-start_time, 3), '.3f'), data["Name"])
            break

        # 请求失败
        # 如果时间在19:59-20:01或者5:59-6:01之间则不间断请求，其他的情况将会每30秒请求一次
        if(eight_time_start <= date <= eight_time_end or six_time_start <= date <= six_time_end):
            end_time = time.perf_counter()
            if(response.text == '{"state":"-104","content":"您当天已经预约过该场馆，不可重复预约。"}'):
                log(str(date), DayName, Secent, "重复预约", format(
                    round(end_time-start_time, 3), '.3f'),data["Name"])
                break
            log(str(date), DayName, Secent, "预约失败", format(
                round(end_time-start_time, 3), '.3f'),data["Name"])
        else:
            # 如果提示重复预约直接退出
            if(response.text == '{"state":"-104","content":"您当天已经预约过该场馆，不可重复预约。"}'):
                break
            end_time = time.perf_counter()
            log(str(date), DayName, Secent, "预约失败", format(
                round(end_time-start_time, 3), '.3f'),data["Name"])
            # 如果超过6:01或者20:01则每30秒请求一次
            time.sleep(30)


# 表示图书馆预约里面的某个界面的id
# 1 是借阅室 15是少儿图书借还处
spaceID = 1
# SceneID标明了预约的时间选项
value = getSceneID(spaceID)
# 更改上方原数据
data["SpaceId"] = spaceID
data["Name"] = "LLrber"
data["IdType"] = "1"
data["IdNumber"] = "身份证号"
data["Mobile"] = "电话"
data["FacilitiesId"]= 4
data["SceneId"] = value[1]
headers["Cookie"] = r"edu_plt=wMpQAmJqnGKovlAqBrIKAg==; culsid=d590e0f215dd6d20; Hm_lvt_41fd2439e008444948375f2bfb9d1901=1654158292; cul=userid=234814&password=YkAMC5H4ER8uNe%2bUuCShqarPRxl58vkxOOVtI8esn9Jlw4P8Xns%2f4PrGqrySM80t; Hm_lpvt_41fd2439e008444948375f2bfb9d1901=1654158304"
headers["Referer"] = "https://www.sjsggwh.com/yuyue/book?id=4&spaceId={}".format(spaceID)
# 执行预约
appointment(str(value[0]), str(value[1]))
